package com.cirnoworks.guice;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.name.Names;

public class PropertiesModule implements Module {

	private final Logger logger = LoggerFactory
			.getLogger(PropertiesModule.class);
	private Map<String, String> properties = new HashMap<String, String>();
	private Map<String, String> propertyFiles = new HashMap<String, String>();

	public PropertiesModule(String... files) {
		for (String file : files) {
			InputStream is = getClass().getResourceAsStream(file);
			if (is == null) {
				logger.warn("Can't find properties file: " + file);
			} else {
				Properties p = new Properties();
				try {
					p.load(is);
				} catch (IOException e) {
					logger.error("Failed in reading properties file: " + file,
							e);
					throw new RuntimeException(e);
				}
				for (Entry<Object, Object> entry : p.entrySet()) {
					String key = (String) entry.getKey();
					String value = (String) entry.getValue();
					String fn = propertyFiles.get(key);
					if (fn != null) {
						logger.warn("Duplicated key [" + key
								+ "] defined in file [" + fn
								+ "] and will be overwritten.");
					}
					propertyFiles.put(key, file);
					properties.put(key, value);
				}
			}
		}
	}

	@Override
	public void configure(Binder binder) {
		Names.bindProperties(binder, properties);
	}

}
